//
//  UPTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/25.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "UPTableViewController.h"
#import "CarTableCellTableViewCell.h"
#import "Puser.h"
#import <MJRefresh.h>
#import "CarDetailmodel.h"
#import "CarlistCellMode.h"
#import "CarDetailViewController.h"
#import "BottomBar.h"
#import "PostCarTableViewController.h"
#import "UserInfoUpdateResde.h"
#import "NoItemView.h"
@interface UPTableViewController ()<BottomBarBtnClickDelegate,BottombarDataSource>{
    BOOL _isedting;
    BOOL _candelete;
}
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) NSMutableArray  *datalist;
@property (nonatomic,strong) NoItemView *noitem;
@end

@implementation UPTableViewController

-(void)BottomBarPostClick:(BottomBar *)bottombar{
    NSLog(@"posttoadd");
    PostCarTableViewController *pvc=[PostCarTableViewController viewcontroller];
    [self.navigationController pushViewController:pvc animated:YES];
    
}
-(NSInteger)numberofBottobarcount:(BottomBar *)bottombar{
    return self.datalist.count;
}
-(void)BottomBar:(BottomBar *)bottombar otherbtnClick:(NSInteger)index{
    NSLog(@"%ld",index);
    if (index==0) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在操作";
        hud.margin = 10.f;
         hud.removeFromSuperViewOnHide = YES;
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
        params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
        if ([self.user.power integerValue]==8) {
            params[@"pid"]=self.user.parent_id;
        }
        params[@"action"]=@"car_down";
        NSMutableArray *IDarray=[NSMutableArray array];
        for (CarlistCellMode *mode in self.datalist) {
            if (mode.ischecked) {
                [IDarray addObject:mode.cardmode.ID];
            }
        }
        params[@"car_id"]=[NSString DataTOjsonString:IDarray];
        
        [PostUitls Post:mycarsource parameters:params success:^(id response) {
            UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
            if ([resdmode.state integerValue]==400) {
                [self.tableView.header beginRefreshing];
                 _candelete=NO;
                self.bottombar.btnenable=_candelete;
                self.bottombar.allselected=_candelete;
                NSDictionary *userinfo=@{@"down":@"1"};
                
                NSNotification *nocite=
                [[NSNotification alloc] initWithName:NoticeCarNeddUpdate object: nil userInfo:userinfo];
                
                [[NSNotificationCenter defaultCenter] postNotification:nocite];
            }
            hud.labelText=resdmode.msg;
            hud.mode = MBProgressHUDModeText;
            [hud hide:YES afterDelay:1];
        } failure:^(NSError *error) {
            hud.labelText=@"网络错误";
            hud.mode = MBProgressHUDModeText;
        }];

    }else{
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        hud.labelText=@"正在操作";
        hud.margin = 10.f;
        hud.removeFromSuperViewOnHide = YES;
        NSMutableDictionary *params=[NSMutableDictionary dictionary];
        params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
        params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
        if ([self.user.power integerValue]==8) {
            params[@"pid"]=self.user.parent_id;
        }
        params[@"action"]=@"car_refresh";
        NSMutableArray *IDarray=[NSMutableArray array];
        for (CarlistCellMode *mode in self.datalist) {
            if (mode.ischecked) {
                [IDarray addObject:mode.cardmode.ID];
            }
        }
        params[@"car_id"]=[NSString DataTOjsonString:IDarray];
        
        [PostUitls Post:mycarsource parameters:params success:^(id response) {
            UserInfoUpdateResde *resdmode=[UserInfoUpdateResde resdeWithDict:response];
            if ([resdmode.state integerValue]==400) {
                [self.tableView.header beginRefreshing];
                _candelete=NO;
                self.bottombar.btnenable=_candelete;
                self.bottombar.allselected=_candelete;
            }
            hud.labelText=resdmode.msg;
            hud.mode = MBProgressHUDModeText;
            [hud hide:YES afterDelay:1];
        } failure:^(NSError *error) {
            hud.labelText=@"网络错误";
            hud.mode = MBProgressHUDModeText;
        }];

    }
}

-(void)BottomBarAllclick:(BottomBar *)bottombar{
    NSLog(@"all");
    for (CarlistCellMode *mode in self.datalist) {
        mode.ischecked=bottombar.allselected;
    }
    [self.tableView reloadData];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.tableView.contentInset=UIEdgeInsetsMake(0, 0, 56, 0);
    self.tableView.backgroundColor=bgGarycolor;
    [self setuptablevew];
   
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editchange:) name:NoticeIsEidt object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(needupdate:) name:NoticeCarNeddUpdate object:nil];
   _noitem=[NoItemView viewWithType:MYCARTYPE];
    [self.view addSubview:_noitem];
   self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    
}
-(void)needupdate:(NSNotification *)notice{
    NSString *up=notice.userInfo[@"up"];
    if ([up integerValue]==1) {
        [self.tableView.header beginRefreshing];
    }
}
-(void)editchange:(NSNotification *)notice{
    NSNumber *state=notice.userInfo[@"iseiting"];
    _isedting=[state boolValue];
    if ([state integerValue]==0) {
        for (CarlistCellMode *mode in self.datalist) {
            if (mode.ischecked) {
                mode.ischecked=NO;
            }
        }
        self.bottombar.allselected=NO;
    }
    [self.tableView reloadData];
}

-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView.header beginRefreshing];
}
-(void)setuptablevew{
    self.tableView.header=[MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refresh)];
    self.tableView.footer=[MJRefreshBackNormalFooter footerWithRefreshingTarget: self refreshingAction:@selector(loadmore)];
   
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
        
    }

}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
}
-(void)refresh{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"car_source";
    params[@"num"]=Kpagesize;
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    if ([self.user.power integerValue]==8) {
        params[@"pid"]=self.user.parent_id;
    }
    params[@"car_state"]=@"up";
    [PostUitls Post:mycarsource parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            [self.noitem hide];
            [self.datalist removeAllObjects];
            NSString *truename=dict[@"truename"];
            NSMutableArray *marray=[NSMutableArray array];
            for (NSDictionary *ddict in dict[@"data"]) {
                CarDetailmodel *detail=[CarDetailmodel carWithdict:ddict];
                detail.truename=truename;
                CarlistCellMode *mode=[[CarlistCellMode alloc]init];
                mode.cardmode=detail;
                
                [marray addObject:mode];
            }
            [self.datalist addObjectsFromArray:marray];
            if (marray.count<[Kpagesize integerValue]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                [self.tableView.footer resetNoMoreData];
            }
            if (self.datalist.count==0) {
                NSLog(@"没有上架的车源");
                [self.noitem show];
            }
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }else{
            if (self.datalist.count==0) {
                NSLog(@"没有上架的车源");
                [self.noitem show];
            }
             [self.tableView.header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        [self.tableView.header endRefreshing];
    }];
    
    
}



-(void)loadmore{
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"car_source";
    params[@"num"]=Kpagesize;
    params[@"user_id"]=[self.user.power integerValue]<5?self.user.user_id:self.user.com_id;
    params[@"type"]=[self.user.power integerValue]<5?@"person":@"company";
    if ([self.user.power integerValue]==8) {
        params[@"pid"]=self.user.parent_id;
    }
     params[@"car_state"]=@"up";
    NSMutableArray *IDarray=[NSMutableArray array];
    
    for (CarlistCellMode *mode in self.datalist) {
        [IDarray addObject:mode.cardmode.ID];
    }
    params[@"page_id"]=[NSString DataTOjsonString:IDarray];
    
    [PostUitls Post:mycarsource parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            
            NSString *truename=dict[@"truename"];
            NSMutableArray *marray=[NSMutableArray array];
            for (NSDictionary *ddict in dict[@"data"]) {
                CarDetailmodel *detail=[CarDetailmodel carWithdict:ddict];
                detail.truename=truename;
                CarlistCellMode *mode=[[CarlistCellMode alloc]init];
                mode.cardmode=detail;
                
                [marray addObject:mode];
            }
            [self.datalist addObjectsFromArray:marray];
            if (marray.count<[Kpagesize integerValue]) {
                [self.tableView.footer noticeNoMoreData];
            }else{
                [self.tableView.footer resetNoMoreData];
            }
            
            [self.tableView reloadData];
            [self.tableView.header endRefreshing];
        }
        
    } failure:^(NSError *error) {
        MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
        
        hud.labelText=@"网络错误";
        hud.mode = MBProgressHUDModeText;
        
        hud.margin = 10.f;
        
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:1];
        [self.tableView.header endRefreshing];
    }];

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_isedting) {
        CarlistCellMode *mode=self.datalist[indexPath.row];
        mode.ischecked=!mode.ischecked;
        CarTableCellTableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
        cell.editbtn.selected=!cell.editbtn.selected;
        for (CarlistCellMode *carmode in self.datalist) {
            if (carmode.ischecked) {
                _candelete=YES;
                break;
            }else{
                _candelete=carmode.ischecked;
            }
        }
        self.bottombar.btnenable=_candelete;
    }else{
        CarlistCellMode *mode=self.datalist[indexPath.row];
        CarDetailViewController *cadvc=[CarDetailViewController viewcontroller];
        cadvc.ID=mode.cardmode.ID;
        [self.navigationController pushViewController:cadvc animated:YES];
    }
}
-(NSMutableArray *)datalist{
    if (_datalist==nil) {
        _datalist=[NSMutableArray array];
    }
    return _datalist;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return self.datalist.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarTableCellTableViewCell *cell=[CarTableCellTableViewCell cellWithTableView:tableView];
    cell.carcellmode=self.datalist[indexPath.row];
    cell.isShowEidt=_isedting;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CarlistCellMode *mode=self.datalist[indexPath.row];
    return mode.rowheight;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
